package com.xiaoshuidi.cloud.module.system.service.apartment;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.xiaoshuidi.cloud.framework.common.enums.CommonStatusEnum;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.datapermission.core.rule.dept.DeptDataPermissionRule;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.context.TenantContextHolder;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.ApartmentApi;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.vo.ApartmentListRespVO;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.RoomHouseApi;
import com.xiaoshuidi.cloud.module.system.api.apartment.dto.TaxRateConfigDTO;
import com.xiaoshuidi.cloud.module.system.api.dept.dto.DeptLeaderRespDTO;
import com.xiaoshuidi.cloud.module.system.api.permission.dto.DeptDataPermissionRespDTO;
import com.xiaoshuidi.cloud.module.system.controller.admin.apartment.vo.ApartmentListReqVO;
import com.xiaoshuidi.cloud.module.system.controller.admin.apartment.vo.ApartmentRespVO;
import com.xiaoshuidi.cloud.module.system.controller.admin.dept.vo.dept.DeptCreateReqVO;
import com.xiaoshuidi.cloud.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import com.xiaoshuidi.cloud.module.system.controller.admin.dept.vo.dept.DeptUpdateReqVO;
import com.xiaoshuidi.cloud.module.system.convert.apartment.ApartmentConvert;
import com.xiaoshuidi.cloud.module.system.convert.dept.DeptConvert;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.apartment.ApartmentDO;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.dept.DeptDO;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.user.AdminUserDO;
import com.xiaoshuidi.cloud.module.system.dal.mysql.apartment.ApartmentMapper;
import com.xiaoshuidi.cloud.module.system.dal.mysql.dept.DeptMapper;
import com.xiaoshuidi.cloud.module.system.dal.mysql.user.AdminUserMapper;
import com.xiaoshuidi.cloud.module.system.enums.apartment.ApartmentManageEnum;
import com.xiaoshuidi.cloud.module.system.enums.dept.DeptIdEnum;
import com.xiaoshuidi.cloud.module.system.mq.producer.dept.DeptProducer;
import com.xiaoshuidi.cloud.module.system.service.dept.DeptService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.validation.annotation.Validated;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

import static com.xiaoshuidi.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xiaoshuidi.cloud.module.system.enums.ErrorCodeConstants.*;

/**
 * 门店管理 Service 实现类
 *
 * @author
 */
@Service
@Validated
@Slf4j
public class ApartmentServiceImpl implements ApartmentService {


    @Resource
    private ApartmentMapper apartmentMapper;
    @Resource
    private ApartmentApi apartmentApi;

    @Override
    public List<TaxRateConfigDTO> getConfigFeesList(Long apartmentId) {
        return apartmentMapper.getConfigFeesList(apartmentId);
    }

    /**
     * 创建门店管理
     * @param apartmentId 门店id
     * @param apartmentName 门店名称
     * @return 门店编号
     */
    @Override
    public Long createApartment(Long apartmentId,String apartmentName) {

        //判断新增门店是否存在
        List<ApartmentDO> apartmentDOS = apartmentMapper.selectList(ApartmentDO::getApartmentId, apartmentId);
        if (CollectionUtils.isNotEmpty(apartmentDOS)){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "该门店已经存在!");
        }
        ApartmentDO apartmentDO = new ApartmentDO();
        apartmentDO.setApartmentId(apartmentId);
        apartmentDO.setApartmentName(apartmentName);
        apartmentMapper.insert(apartmentDO);

        return apartmentDO.getId();
    }

    /**
     * 筛选门店列表
     *
     * @param reqVO 筛选条件请求 VO
     * @return 部门列表
     */
    @Override
    public PageResult<ApartmentRespVO> getApartmentList(ApartmentListReqVO reqVO) {
        //判断状态是否为空，为空默认为已配置
        if (Objects.isNull(reqVO.getStatus())){
            reqVO.setStatus(1);
        }
        LambdaQueryWrapper<ApartmentDO> qw = new LambdaQueryWrapper<>();

        if (reqVO.getStatus() == 0){
            qw.eq(ApartmentDO::getCollectionConfig,0)
                    .or().eq(ApartmentDO::getContractConfig,0)
                    //.or().eq(ApartmentDO::getInvoiceConfig,0)
                    .or().eq(ApartmentDO::getOrderConfig,0)
                    .or().eq(ApartmentDO::getReceiptConfig,0)
                    //.or().eq(ApartmentDO::getTaxRateConfig,0)
                    ;
        } else {
            qw.eq(ApartmentDO::getCollectionConfig,1)
                    .eq(ApartmentDO::getContractConfig,1)
                    //.eq(ApartmentDO::getInvoiceConfig,1)
                    .eq(ApartmentDO::getOrderConfig,1)
                    .eq(ApartmentDO::getReceiptConfig,1)
                    //.eq(ApartmentDO::getTaxRateConfig,1)
                    ;
        }
        qw.like(StringUtils.isNotBlank(reqVO.getName()),ApartmentDO::getApartmentName,reqVO.getName())
                .orderByDesc(ApartmentDO::getUpdateTime);
        PageResult<ApartmentDO> apartmentDOPageResult = apartmentMapper.selectPage(reqVO, qw);
        return ApartmentConvert.INSTANCE.convertPage(apartmentDOPageResult);
    }

    /**
     * 修改门店对应配置（第一次创建配置时调用即可）
     *
     * @param apartmentId             门店id
     * @param apartmentManageEnumCode 配置编号
     * @return 门店编号
     */
    @Override
    public Boolean updateApartment(Long apartmentId, Integer apartmentManageEnumCode) {
        LambdaUpdateWrapper<ApartmentDO> uw = new LambdaUpdateWrapper<>();
        uw.eq(ApartmentDO::getApartmentId,apartmentId)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.CONTRACT_CONFIG.getCode()),ApartmentDO::getContractConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.ORDER_CONFIG.getCode()),ApartmentDO::getOrderConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.COLLECTION_CONFIG.getCode()),ApartmentDO::getCollectionConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.INVOICE_CONFIG.getCode()),ApartmentDO::getInvoiceConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.RECEIPT_CONFIG.getCode()),ApartmentDO::getReceiptConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.TAX_RATE_CONFIG.getCode()),ApartmentDO::getTaxRateConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.CERTIFICATE_CONFIG.getCode()),ApartmentDO::getCertificateConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.SETTLEMENTACCOUNT_CONFIG.getCode()),ApartmentDO::getSettlementAccount,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.TAX_RATE_CONFIG.getCode()),ApartmentDO::getTaxRateConfig,1)
                .set(Objects.nonNull(apartmentManageEnumCode) && Objects.equals(apartmentManageEnumCode, ApartmentManageEnum.INFORM_CONFIG.getCode()),ApartmentDO::getInformConfig,1);
        int update = apartmentMapper.update(null, uw);
        if (update > 0){
            return true;
        }
        return false;
    }

    /**
     * 初始化门店管理列表
     */
    @Override
    public void initialization() {
        //获取租户下的所有门店
        List<ApartmentListRespVO> data = apartmentApi.apartmentAllList().getData();
        if (CollectionUtils.isNotEmpty(data)){
            List<ApartmentDO> list = new ArrayList<>();
            data.forEach(v->{
                ApartmentDO apartmentDO = new ApartmentDO();
                apartmentDO.setApartmentId(v.getId());
                apartmentDO.setApartmentName(v.getName());
                list.add(apartmentDO);
            });
            apartmentMapper.insertBatch(list);
        }
    }

    @Override
    public void updateApartmentName(Long apartmentId, String name) {
        if (Objects.isNull(apartmentId) || Objects.isNull(name)){
            log.error("更新门店名称参数异常");
            return;
        }
        LambdaUpdateWrapper<ApartmentDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApartmentDO::getApartmentId, apartmentId);
        updateWrapper.set(ApartmentDO::getApartmentName, name);
        apartmentMapper.update(null, updateWrapper);
    }

}
